package models

import (
	"log"
)

type Message struct {
	Model
	Content string `gorm:"size:255" json:"content"`
	Uid     string `gorm:"type:char(36)" json:"uid"`
	View    int32  `gorm:"default:0" json:"view"`
}

// 添加留言
func (a *Message) AddMessage(uuid string) (bool, error) {
	var check Message

	if check.Content != "" {
		return false, nil
	}

	a.Uid = uuid

	err := db.Create(a).Error

	log.Println("err:", err)
	log.Println("插入后:", a)
	log.Println("获取插入后生成的UUID:", a.UUID)
	return true, err
}

type Messages struct {
	Uuid     string `json:"uuid"`
	Content  string `json:"content"`
	Uid      string `json:"uid"`
	UserName string `json:"user_name"`
}

//留言列表
func (a *Message) ListMessage(page, pageSize int) []Messages {
	// list := make([]Messages, pageSize)

	var list []Messages

	// err := db.Limit(pageSize).Offset((page - 1) * pageSize).Find(&list).Error

	if err := db.Select("messages.content, messages.uuid, messages.uid, accounts.user_name").Where("messages.deleted_at = 0").Joins("inner join accounts on accounts.uuid = messages.uid").Limit(pageSize).Offset((page - 1) * pageSize).Find(&list).Error; err != nil {
		log.Println("sql：", err)
	}

	return list
}

//留言详情
func (a *Message) DetailMessage(id string) Messages {
	var detail Messages

	if err := db.Select("messages.content, messages.uuid, messages.uid, accounts.user_name, messages.created_at").Where("messages.uuid = ? and messages.deleted_at = 0", id).Joins("inner join accounts on accounts.uuid = messages.uid").First(&detail).Error; err != nil {
		log.Println(err)
	}

	return detail
}

//删除留言
func (a *Message) DelMessage(id, uuid string) (bool, error) {

	// 带额外条件的删除
	if err := db.Where("uuid = ? and uid = ?", id, uuid).Delete(&a).Error; err != nil {
		log.Println("sql", err)
		return false, nil
	}

	return true, nil
}
